package com.abel.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.abel.domain.UserSession;
import com.abel.util.UserSessionLocator;

/**
 * Servlet Filter implementation class UserSessionFilter
 * It intercepts all request are sets the UserSession
 * This filter ensures that the user do not access other pages in the 
 * application without login and valid authentication
 */

public class UserSessionFilter implements Filter {

	protected final Log logger = LogFactory.getLog(getClass());
	
    /**
     * Default constructor. 
     */
    public UserSessionFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		//to nothing
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		logger.debug("@UserSessionFilter : doFilter : entered" );
		
		//checks in usersession exists, if null, set it
		HttpSession session = ((HttpServletRequest)request).getSession();
		UserSession userSession = (UserSession)session.getAttribute("USER_SESSION");
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		
		if (userSession == null ) {

			userSession = new UserSession();
			userSession.setId(session.getId());
			session.setAttribute("USER_SESSION", userSession);
			logger.debug("@UserSessionFilter : doFilter : new id set " + userSession.getId());
			//setting the userSession to be available through ThreadLocal 
			UserSessionLocator.setUserSession(userSession);
			//redirecting to login page
			httpResponse.sendRedirect("login.xhtm");
			return;
		}
		else {
			//ensuring that login.xhtm requests are not intercepted
			String path = ((HttpServletRequest)request).getRequestURI();
			
			if (path != null 
					&& !(path.indexOf("/login.xhtm") != -1
							|| path.indexOf("/register.xhtm") != -1
							|| path.indexOf("/forgotPassword.xhtm") != -1
							|| path.indexOf("/processForgotPassword.xhtm") != -1
							//|| path.indexOf("/adminregister.xhtm") != -1
							|| path.indexOf("/adminlogin.xhtm") != -1) 
					&& (userSession.getAuthPrincipal() == null
					|| userSession.getAuthPrincipal().getUserId() <= 0)) {
				
				//setting the userSession to be available through ThreadLocal 
				UserSessionLocator.setUserSession(userSession);

				//redirecting to login page
				httpResponse.sendRedirect("login.xhtm");
				return;
			}
			else {
				if (path == null) {
					
					httpResponse.sendRedirect("error.jsp");
					return;
				
				}
				//setting the userSession to be available through ThreadLocal 
				UserSessionLocator.setUserSession(userSession);
				chain.doFilter(request, response);
			}
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		//do nothing
	}

}
